import React, {useState} from 'react';
import {Upload, message, Space, Modal} from "antd"; // Correct import for Upload
import {PlusOutlined} from "@ant-design/icons";
import _ from "lodash";

function FileUploader(props) {
    const [fileUrlList, setFileUrlList] = useState([]); // 定义上传文件列表
    const [previewModal, setPreviewModal] = useState({ visible: false, url: '' }); // 定义预览图片

    // 初始化 defaultFileList
    const defaultFileList = props.defaultFileList?.map((item, index) => ({
        uid: index,
        url: item,
        status: 'done' // 初始化已上传状态
    })) || [];

    // 上传配置
    const uploadProps = {
        action: '/api/api/upload',
        listType: 'picture-card',
        method: 'post',
        maxCount: props.maxCount || 1, // 上传文件数量
        defaultFileList: defaultFileList,
        headers: {
            Authorization: sessionStorage.getItem('token'), // Replace with your token retrieval method
        },
        onChange: (info) => {
            const { file, fileList } = info;
            if (file.status === 'done') {
                const updatedFileUrls = fileList.map(item => item.url || (item.response && item.response.file.url));
                setFileUrlList(updatedFileUrls);
                props.onChange && props.onChange(updatedFileUrls.join(','));
            } else if (file.status === 'error') {
                message.error('上传失败');
            }
        },
        onRemove: (file) => {
            const updatedFileUrls = _.filter(fileUrlList, (item) => (file.url || (file.response && file.response.file.url)) !== item);
            setFileUrlList(updatedFileUrls);
            props.onChange && props.onChange(updatedFileUrls.join(','));
        },
        onPreview: (file) => {
            setPreviewModal({ visible: true, url: file.url || (file.response && file.response.file.url) });
        }
    };

    return (
        <>
            <Upload {...uploadProps}>
                <Space direction="vertical">
                    <PlusOutlined />
                    <div style={{ margin: 8 }}>上传</div>
                </Space>
            </Upload>
            {previewModal.visible && (
                <Modal
                    title="预览"
                    footer={null}
                    visible={previewModal.visible}
                    onCancel={() => setPreviewModal({ visible: false, url: '' })}
                >
                    <img src={previewModal.url} alt="预览" style={{ width: '100%' }} />
                </Modal>
            )}
        </>
    );
}

export default FileUploader;
